package cn.iocoder.yudao.module.shop.admin.service;

import cn.hutool.core.util.RandomUtil;
import cn.iocoder.yudao.framework.business.basic.enums.RoleCodeV2Enum;
import cn.iocoder.yudao.framework.common.biz.config.ConfigCommonApi;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.datapermission.core.annotation.DataPermission;
import cn.iocoder.yudao.module.api.infrastructure.ConfigConstants;
import cn.iocoder.yudao.module.api.infrastructure.user.AdminUserApiV2;
import cn.iocoder.yudao.module.api.infrastructure.user.dto.AdminUserRespDTO;
import cn.iocoder.yudao.module.api.infrastructure.user.dto.SystemUserCreateReqDTO;
import cn.iocoder.yudao.module.shop.admin.dao.ShopUserMapper;
import cn.iocoder.yudao.module.shop.admin.pojo.po.ShopUser;
import cn.iocoder.yudao.module.shop.admin.pojo.vo.ShopUserCreateReqVO;
import cn.iocoder.yudao.module.shop.admin.pojo.vo.ShopUserPageReqVO;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.api.shop.ErrorCodeConstants.SHOP_ADMIN_NOT_EXISTS;

/**
 * 店铺商户 Service 实现类
 *
 * @author 山野羡民（1032694760@qq.com）
 */
@Service
@Validated
public class ShopUserServiceImpl implements ShopUserService {

    @Resource
    private ShopUserMapper shopUserMapper;

    @Resource
    @Lazy // 延迟加载，避免循环依赖
    private ConfigCommonApi configApi;
    @Resource
    @Lazy // 延迟加载，避免循环依赖
    private AdminUserApiV2 adminUserApiV2;

    @Override
    public Long createAdminIfNecessary(Long shopId, Long userId, String name, String mobile) {
        // 优先使用负责人手机号码注册店铺的后台管理员账号
        AdminUserRespDTO userRespDTO = adminUserApiV2.getByUsername(mobile);
        if (userRespDTO != null) {
            ShopUser shopUserDO = shopUserMapper.selectOne(userRespDTO.getId(), UserTypeEnum.ADMIN.getValue(), shopId);
            if (shopUserDO != null && shopUserDO.getAdminUserId() > 0) {
                // 确保启用
                adminUserApiV2.updateUserStatus(shopUserDO.getAdminUserId(), CommonStatusEnum.ENABLE.getStatus());
                shopUserDO.setMemberUserId(userId);
                shopUserMapper.updateById(shopUserDO);
                return shopUserDO.getAdminUserId();
            }
            // 若手机号码已被其他管理员用户名占用，则随机生成用户名
            mobile = RandomUtil.randomStringUpper(8);
        }
        // 插入管理员用户信息
        String initPassword = configApi.getConfigValueByKey(ConfigConstants.CONFIG_ACCOUNT_INIT_PASSWORD);
        SystemUserCreateReqDTO createReqDTO = new SystemUserCreateReqDTO();
        createReqDTO.setName(name);
        createReqDTO.setUsername(mobile);
        createReqDTO.setPassword(initPassword);
        createReqDTO.setRoleCode(RoleCodeV2Enum.SHOP_ADMIN.getCode());
        createReqDTO.setRemark("平台管理员对店铺审核通过时自动生成");
        Long adminUserId = adminUserApiV2.createUser(createReqDTO);
        ShopUser shopUserDO = shopUserMapper.selectOne(userId, UserTypeEnum.MEMBER.getValue(), shopId);
        // 若前台用户已经是店铺商户，则更新店铺商户信息
        if (shopUserDO != null) {
            shopUserDO.setAdminUserId(adminUserId);
            shopUserDO.setContactName(name);
            shopUserDO.setContactMobile(mobile);
            shopUserMapper.updateById(shopUserDO);
            // 确保启用
            adminUserApiV2.updateUserStatus(adminUserId, CommonStatusEnum.ENABLE.getStatus());
            return adminUserId;
        }
        // 插入店铺商户信息
        shopUserDO = new ShopUser();
        shopUserDO.setShopId(shopId);
        shopUserDO.setMemberUserId(userId);
        shopUserDO.setAdminUserId(adminUserId);
        shopUserDO.setContactName(name);
        shopUserDO.setContactMobile(mobile);
        shopUserMapper.insert(shopUserDO);
        // 确保启用
        adminUserApiV2.updateUserStatus(adminUserId, CommonStatusEnum.ENABLE.getStatus());
        return adminUserId;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long createAdmin(ShopUserCreateReqVO createReqVO) {
        return createAdminIfNecessary(createReqVO.getShopId(), createReqVO.getUserId(), createReqVO.getName(), createReqVO.getMobile());
    }

    @Override
    public void deleteAdmin(Long id) {
        // 校验存在
        ShopUser shopUserDO = validateAdminExists(id);
        // 删除
        shopUserMapper.deleteById(shopUserDO.getId());
    }

    private ShopUser validateAdminExists(Long id) {
        ShopUser shopUserDO = shopUserMapper.selectById(id);
        if (shopUserDO == null) {
            throw exception(SHOP_ADMIN_NOT_EXISTS);
        }
        return shopUserDO;
    }

    @Override
    public ShopUser getAdmin(Long id) {
        return validateAdminExists(id);
    }

    @Override
    public PageResult<ShopUser> getAdminPage(ShopUserPageReqVO pageReqVO) {
        return shopUserMapper.selectPage(pageReqVO);
    }

    @Override
    public List<ShopUser> getAdminListByUserId(Long userId, Integer userType) {
        return shopUserMapper.selectList(userId, userType, null);
    }

    @Override
    @DataPermission(enable = false) // 指定店铺编号查询，需忽略店铺的数据权限
    public List<ShopUser> getAdminListByShopId(Long shopId) {
        return shopUserMapper.selectList(ShopUser::getShopId, shopId);
    }

    @Override
    public ShopUser getAdmin(Long shopId, Long userId, Integer userType) {
        return shopUserMapper.selectOne(userId, userType, shopId);
    }

}
